﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DLL;
using CommonHelpers;

namespace QuanLyBanLe
{
    public partial class FormOrder
    {
        private bool m_returnProductChanged2;

        private void InitReturnProductWithBillMan()
        {
            
        }

        private void LoadReturnProductWithBillMan()
        {
            this.lblCustomerName2.Text = "";
            this.lblTime2.Text = "";
            lblTotalPrice2.Text = "0 Đ";
            lblTotalReturn2.Text = "0 Đ";
            this.dtgBillDetail2.AutoGenerateColumns = false;
            m_returnProductChanged2 = false;
        }

        private void btnFindBill_Click(object sender, EventArgs e)
        {
            ReturnProductReset2();
            int billId = Convert.ToInt32(txtBillId2.Text);
            Bill bill = m_BillService.GetPrintedBill(billId);
            if (bill != null)
            {
                lblCustomerName2.Text = bill.CustomerName;
                lblTime2.Text = bill.SaleTime.ToString(Core.Formats.DateTimeFormat);
                List<pGetBIllDetailByBillId_Result> billDetails = m_BillDetailService.GetBillDetailByBillId(billId);
                dtgBillDetail2.DataSource = billDetails;
                int totalPrice = 0;
                foreach (var billDetail in billDetails)
                {
                    totalPrice += billDetail.TotalPrice.Value;
                }
                lblTotalPrice2.Text = totalPrice.ToMoney();
            }
            else
            {
                MessageBox.Show("Không tìn thấy hóa đơn này", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnReturnProduct_Click(object sender, EventArgs e)
        {
            var currentRow = dtgBillDetail2.CurrentRow;
            if (currentRow != null)
            {
                // Check billDetail Id already exist in Return Product Grid
                int billDetailId = Convert.ToInt32(currentRow.Cells["colBillDetailId2"].Value);
                bool isExisted = IsBillDetailAddedToReturnProduct(billDetailId);
                if (isExisted)
                {
                    MessageBox.Show("Sản phẩm này đã nằm trong danh sách trả hàng, nếu muốn trả thêm bạn phải tăng số lượng trả", "Thông báo",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    int saleAmount = Convert.ToInt32(currentRow.Cells["colAmount2"].Value);
                    if (saleAmount > 0)
                    {
                        dtgReturnProducts2.Rows.Add(1);
                        int index = dtgReturnProducts2.Rows.Count - 1;
                        DataGridViewRow row = dtgReturnProducts2.Rows[index];
                        row.Cells["colRowNumber4"].Value = index + 1;
                        row.Cells["colProduct4"].Value = currentRow.Cells["colProduct2"].Value;
                        row.Cells["colSalePrice4"].Value = currentRow.Cells["colSalePrice2"].Value;
                        row.Cells["colAmountReturn4"].Value = 1;
                        row.Cells["colMaxAmount4"].Value = saleAmount;
                        row.Cells["colTotalPrice4"].Value = currentRow.Cells["colSalePrice2"].Value;
                        row.Cells["colBillDetailId4"].Value = currentRow.Cells["colBillDetailId2"].Value;
                        m_returnProductChanged2 = true;
                    }
                    else
                    {
                        MessageBox.Show("Sản phẩm này trả hết nên không thể trả thêm", "Thông báo",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                MessageBox.Show("Chọn 1 chi tiết hóa đơn trước khi trả hàng", "Thông báo",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void ReturnProductReset2()
        {
            m_returnProductChanged2 = false;
            this.lblCustomerName2.Text = "";
            this.lblTime2.Text = "";
            lblTotalPrice2.Text = "0 Đ";
            lblTotalReturn2.Text = "0 Đ";
            dtgBillDetail2.DataSource = null;
            dtgBillDetail2.Rows.Clear();
            dtgReturnProducts2.DataSource = null;
            dtgReturnProducts2.Rows.Clear();
        }

        private void AddItemsToBillDetailGrid2(List<pGetBIllDetailByBillId_Result> billDetails)
        {
            dtgBillDetail2.Rows.Clear(); // Clear old data
            int i = 0;
            foreach (pGetBIllDetailByBillId_Result billDetail in billDetails)
            {
                dtgBillDetail2.Rows.Add(1);
                DataGridViewRow row = dtgBillDetail2.Rows[i];
                row.Cells["colRowNumber2"].Value = billDetail.RowNumber;
                row.Cells["colProduct2"].Value = billDetail.Name;
                row.Cells["colSalePrice2"].Value = billDetail.SalePrice;
                row.Cells["colAmount2"].Value = billDetail.Amount;
                row.Cells["colTotalPrice2"].Value = billDetail.TotalPrice;
                row.Cells["colBillDetailId2"].Value = billDetail.Id;
                i++;
            }
        }

        private bool SaveReturnProduct2()
        {
            ReturnProduct returnProduct = new ReturnProduct
            {
                ReturnDate = dtpReturnDate2.Value,
                Comment = txtComment2.Text
            };
            List<ReturnProductDetail> details = new List<ReturnProductDetail>();
            foreach (DataGridViewRow row in dtgReturnProducts2.Rows)
            {
                if (!row.IsNewRow)
                {
                    ReturnProductDetail detail = new ReturnProductDetail();
                    detail.BillDetailId = Convert.ToInt32(row.Cells["colBillDetailId4"].Value);
                    detail.Amount = Convert.ToInt32(row.Cells["colAmountReturn4"].Value);
                    details.Add(detail);
                }
            }
            var result = m_returnProductService.AddReturnProductWithBill(returnProduct, details);
            return result;
        }

        private bool IsBillDetailAddedToReturnProduct(int billDetailId)
        {
            bool isExisted = false;
            for (int i = 0; i < dtgReturnProducts2.Rows.Count; i++)
            {
                int returnBillDetailId = Convert.ToInt32(dtgReturnProducts2.Rows[i].Cells["colBillDetailId4"].Value);
                if (returnBillDetailId == billDetailId)
                {
                    isExisted = true;
                    break;
                }
            }
            return isExisted;
        }

        private void CalculateTotalReturnProductPrice2()
        {
            int totalPrice = 0;
            foreach (DataGridViewRow row in this.dtgReturnProducts2.Rows)
            {
                var temp = row.Cells["colTotalPrice4"].Value;
                if (temp != null)
                {
                    int itemPrice = 0;
                    if (int.TryParse(temp.ToString(), out itemPrice))
                    {
                        totalPrice += itemPrice;
                    }
                }
            }

            lblTotalReturn2.Text = totalPrice.ToMoney();
        }

        private void ReturnProductEnableControls2(bool enable)
        {
            dtgReturnProducts2.ReadOnly = !enable;
            txtComment2.Enabled = enable;
            txtBillId2.Enabled = enable;
            dtpReturnDate2.Enabled = enable;
            btnReturnProduct2.Enabled = enable;
            btnSaveReturn2.Enabled = enable;
            btnFindBill2.Enabled = enable;
        }

        private void dtgReturnProducts2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dtgReturnProducts2.Columns["colDelete4"].Index)
            {
                DialogResult result = MessageBox.Show("Bạn có chắc muốn xóa chi tiết trả hàng này", "Thông báo",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    dtgReturnProducts2.Rows.RemoveAt(e.RowIndex);
                    CalculateTotalReturnProductPrice2();
                }
            }
        }

        private void dtgReturnProducts2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            var currentRow = dtgReturnProducts2.Rows[e.RowIndex];
            if (e.ColumnIndex == currentRow.Cells["colAmountReturn4"].ColumnIndex)
            {
                int salePrice = Convert.ToInt32(currentRow.Cells["colSalePrice4"].Value);
                int amount = Convert.ToInt32(currentRow.Cells["colAmountReturn4"].Value);
                int totalPrice = salePrice * amount;
                currentRow.Cells["colTotalPrice4"].Value = totalPrice;
                CalculateTotalReturnProductPrice2();
            }
        }

        private void dtgReturnProducts2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            var currentRow = dtgReturnProducts2.Rows[e.RowIndex];
            if (currentRow.IsNewRow) { return; }

            currentRow.ErrorText = "";
            bool isValid = true;

            // validate return amount
            if (e.ColumnIndex == dtgReturnProducts2.Columns["colAmountReturn4"].Index)
            {
                if (e.FormattedValue == null)
                {
                    isValid = false;
                    currentRow.ErrorText = "Nhập số lượng trả";
                }
                else
                {
                    int amount;
                    bool parseSuccess = int.TryParse(e.FormattedValue.ToString(), out amount);
                    if (parseSuccess)
                    {
                        if (amount <= 0)
                        {
                            isValid = false;
                            currentRow.ErrorText = "Sai số lượng";
                        }
                        else
                        {
                            int maxAmount = Convert.ToInt32(currentRow.Cells["colMaxAmount4"].Value);
                            if (amount > maxAmount)
                            {
                                isValid = false;
                                currentRow.ErrorText = "Số lượng trả phải nhỏ hơn hoặc bằng số lượng đã mua";
                            }
                        }
                    }
                    else
                    {
                        isValid = false;
                        currentRow.ErrorText = "Sai số lượng";
                    }
                }
            }

            e.Cancel = !isValid;
        }

        private void btnReturnProductSave2_Click(object sender, EventArgs e)
        {
            try
            {
                bool success = SaveReturnProduct2();
                if (success)
                {
                    MessageBox.Show("Đã trả hàng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ReturnProductEnableControls2(false);
                }
                else
                {
                    MessageBox.Show("Có lổi xảy ra, không trả hàng thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (ex.InnerException != null)
                {
                    MessageBox.Show(ex.InnerException.Message);
                }
            }
        }

        private void btnNewReturnProduct2_Click(object sender, EventArgs e)
        {
            ReturnProductReset2();
            txtBillId2.Text = "";
            txtComment2.Text = "";
            ReturnProductEnableControls2(true);
        }

    }
}
